package com.example.demo.hcontroller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.pojo.User;
import com.example.demo.service.IUserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
@RequestMapping(value = "/huser")
public class HUserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/touser")
    private String home(Model model, User user) {
        List<User> list = userService.selectAllUser(user);
        model.addAttribute("userlist", list);
        return "user";
    }

    @RequestMapping("/deleteuser")
    private String deleteuser(Model model, User user, Integer id) {
        userService.deleteUser(id);
        return "redirect:touser";
    }


    @RequestMapping("/toupdateuser")
    private String toupdateuser(Model model, User user, Integer id) {
        user = userService.selectUserById(id);
        model.addAttribute("user", user);
        return "updateuser";
    }

    @RequestMapping("/toadduser")
    public String toadduser() throws UnsupportedEncodingException {

        return "adduser";
    }

    @RequestMapping("/adduser")
    public String addadmin(Model model, User user, Integer sex, String name, String password, Integer age, String tel,
                           String email) throws UnsupportedEncodingException {
        user.setUser_name(name);
        user.setUser_password(password);
        user.setUser_tel(tel);
        user.setUser_email(email);
        user.setUser_age(age);
        user.setUser_gender(sex);
        userService.inserUser(user);
        return "redirect:touser";
    }


    @RequestMapping("/updateuser")
    public String updateuser(HttpServletRequest request, HttpServletResponse response, Model model, User user, Integer sex, String name, String password, Integer age, String tel,
                             String email, Integer id) throws IOException, ServletException {
        user.setUser_name(name);
        user.setId(id);
        user.setUser_password(password);
        user.setUser_tel(tel);
        user.setUser_email(email);
        user.setUser_age(age);
        user.setUser_gender(sex);
        userService.updateUser(user);
        return "redirect:touser";
    }

}
